package com.example.triprec.ui.activity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.triprec.R;
import com.example.triprec.common.Result;
import com.example.triprec.common.ScenicData;
import com.example.triprec.dao.CollectDao;
import com.example.triprec.dao.CommentDao;
import com.example.triprec.entity.Comment;
import com.example.triprec.entity.Scenic;
import com.example.triprec.ui.adapter.ScenicDetailCommentAdapter;
import com.example.triprec.ui.adapter.ScenicDetailImageAdapter;
import com.example.triprec.ui.adapter.ScenicDetailTagAdapter;
import com.example.triprec.ui.dialog.EditTripDialog;
import com.example.triprec.utils.CurrentUserUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 景点详情页Activity
 */
public class ScenicDetailActivity extends AppCompatActivity {

    // 页面控件
    private ImageView ivScenicImage;
    private TextView tvScenicName;
    private TextView tvScore;
    private TextView tvCommentCount;
    private TextView tvLocation;
    private TextView tvOpeningTime;
    private TextView tvPrice;
    private TextView tvDescription;
    private RecyclerView rvTags;
    private RecyclerView rvImages;
    private RecyclerView rvComments;
    private TextView tvBottomPrice;
    private Button btnAddToTrip;
    private ImageButton ibBack;
    private ImageButton ibFavorite;

    // 景点数据
    private Scenic scenic;
    private List<Comment> commentList;

    // 收藏状态
    private boolean isCollected = false;

    // 当前用户ID
    private Long currentUserId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scenic_detail);

        // 获取当前用户ID
        currentUserId = CurrentUserUtils.getCurrentUser().getId();

        // 初始化控件
        initViews();

        // 设置点击事件
        setClickListeners();

        // 加载数据
        loadScenicData();
    }

    /**
     * 初始化控件
     */
    private void initViews() {
        ivScenicImage = findViewById(R.id.iv_scenic_image);
        tvScenicName = findViewById(R.id.tv_scenic_name);
        tvScore = findViewById(R.id.tv_score);
        tvCommentCount = findViewById(R.id.tv_comment_count);
        tvLocation = findViewById(R.id.tv_location);
        tvOpeningTime = findViewById(R.id.tv_opening_time);
        tvPrice = findViewById(R.id.tv_price);
        tvDescription = findViewById(R.id.tv_description);
        rvTags = findViewById(R.id.rv_tags);
        rvImages = findViewById(R.id.rv_images);
        rvComments = findViewById(R.id.rv_comments);
        tvBottomPrice = findViewById(R.id.tv_bottom_price);
        btnAddToTrip = findViewById(R.id.btn_add_to_trip);
        ibBack = findViewById(R.id.ib_back);
        ibFavorite = findViewById(R.id.ib_favorite);
    }

    /**
     * 设置点击事件
     */
    private void setClickListeners() {
        // 返回按钮
        ibBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        // 收藏按钮
        ibFavorite.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toggleCollect();
            }
        });

        // 加入行程按钮
        btnAddToTrip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showAddTripDialog();
            }
        });
    }

    /**
     * 显示添加行程对话框
     */
    private void showAddTripDialog() {
        if (scenic == null || currentUserId == null) {
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            return;
        }
        EditTripDialog dialog = new EditTripDialog(this, currentUserId, scenic.getId(), scenic.getName());
        dialog.show();
    }

    /**
     * 切换收藏状态
     */
    private void toggleCollect() {
        if (scenic == null || currentUserId == null) {
            Toast.makeText(ScenicDetailActivity.this, "请先登录", Toast.LENGTH_SHORT).show();
            return;
        }

        if (isCollected) {
            // 已收藏，执行取消收藏
            Result<Void> result = CollectDao.cancelCollect(currentUserId, scenic.getId());
            if (result.isSuccess()) {
                isCollected = false;
                updateFavoriteIcon();
                Toast.makeText(ScenicDetailActivity.this, "已取消收藏", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(ScenicDetailActivity.this, result.getMessage(), Toast.LENGTH_SHORT).show();
            }
        } else {
            // 未收藏，执行收藏
            Result<Void> result = CollectDao.addCollect(currentUserId, scenic.getId());
            if (result.isSuccess()) {
                isCollected = true;
                updateFavoriteIcon();
                Toast.makeText(ScenicDetailActivity.this, "收藏成功", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(ScenicDetailActivity.this, result.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * 更新收藏图标状态
     */
    private void updateFavoriteIcon() {
        if (isCollected) {
            ibFavorite.setImageResource(R.drawable.ic_favorite_selected);
        } else {
            ibFavorite.setImageResource(R.drawable.ic_favorite_normal);
        }
    }

    /**
     * 加载景点数据
     */
    private void loadScenicData() {
        Long scenicId = getIntent().getLongExtra("scenic_id", 0);
        if (scenicId == 0) {
            Toast.makeText(this, "景点信息获取失败", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        // 加载景点数据
        loadScenicDetail(scenicId);

        // 加载评论数据
        loadComments(scenicId);

        // 检查收藏状态
        checkCollectionStatus(scenicId);
    }

    /**
     * 检查收藏状态
     */
    private void checkCollectionStatus(Long scenicId) {
        if (currentUserId != null) {
            Result<Boolean> result = CollectDao.isCollected(currentUserId, scenicId);
            if (result.isSuccess()) {
                isCollected = result.getData();
                updateFavoriteIcon();
            }
        }
    }

    /**
     * 加载景点详情
     */
    private void loadScenicDetail(Long scenicId) {
        scenic = ScenicData.getScenicById(scenicId);

        // 更新UI
        updateScenicUI();
    }

    /**
     * 更新景点UI
     */
    private void updateScenicUI() {
        if (scenic == null) {
            return;
        }

        // 设置景点名称
        tvScenicName.setText(scenic.getName());

        // 设置位置信息
        tvLocation.setText(scenic.getLocation());

        // 设置开放时间
        tvOpeningTime.setText(scenic.getOpening());

        // 设置门票价格
        String priceText = String.format("¥%.0f", scenic.getPrice());
        tvPrice.setText(priceText + "/人");
        tvBottomPrice.setText(priceText);

        // 设置景点描述
        tvDescription.setText(scenic.getDescription());

        // 设置景点图片
        if (scenic.getImageResources() != null && scenic.getImageResources().length > 0) {
            ivScenicImage.setImageResource(scenic.getImageResources()[0]);

            ScenicDetailImageAdapter adapter = new ScenicDetailImageAdapter(rvImages);
            List<Integer> list = new ArrayList<>(Arrays.asList(scenic.getImageResources()));
            adapter.setData(list);
        }

        // 设置标签
        if (scenic.getCategories() != null && scenic.getCategories().length > 0) {
            ScenicDetailTagAdapter tagAdapter = new ScenicDetailTagAdapter(rvTags);
            rvTags.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
            List<String> tags = new ArrayList<>(Arrays.asList(scenic.getCategories()));
            tagAdapter.setData(tags);
        }
    }

    /**
     * 加载评论数据
     */
    private void loadComments(Long scenicId) {
        Result<List<Comment>> result = CommentDao.getCommentsByScenicId(scenicId);
        if (result.isSuccess()) {
            commentList = result.getData();
            updateCommentsUI();

            // 更新评分
            updateRating();
        } else {
            Toast.makeText(this, result.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 更新评分
     */
    private void updateRating() {
        Result<Double> ratingResult = CommentDao.getAverageScenicScore(scenic.getId());
        if (ratingResult.isSuccess()) {
            Double score = ratingResult.getData();
            // 设置评分
            tvScore.setText(String.format("%.1f", score));

            // 设置评论数量
            String commentCountText = "(" + (commentList == null ? 0 : commentList.size()) + "条评价)";
            tvCommentCount.setText(commentCountText);
        }
    }

    /**
     * 更新评论UI
     */
    private void updateCommentsUI() {
        if (commentList == null || commentList.isEmpty()) {
            return;
        }

        ScenicDetailCommentAdapter adapter = new ScenicDetailCommentAdapter(rvComments);
        adapter.setData(commentList);

    }

} 